const { diaryApi } = require('../../utils/api');

Page({
  data: {
    diary: null,
    loading: true
  },

  onLoad: function(options) {
    console.log('Diary detail page options:', options);
    if (!options || !options.id) {
      console.error('No diary ID provided');
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    
    const diaryId = options.id;
    console.log('Loading diary with ID:', diaryId);
    this.loadDiaryDetail(diaryId);
  },

  async loadDiaryDetail(id) {
    try {
      this.setData({ loading: true });
      console.log('Fetching diary detail for ID:', id);
      const response = await diaryApi.getDiaryDetail(id);
      console.log('Received diary data:', response);
      
      if (!response || !response.data) {
        throw new Error('获取日记详情失败');
      }

      // 处理图片数据
      let images = [];
      if (response.data.images) {
        try {
          if (Array.isArray(response.data.images)) {
            images = response.data.images;
          } else if (typeof response.data.images === 'string') {
            if (response.data.images.startsWith('[') || response.data.images.startsWith('{')) {
              images = JSON.parse(response.data.images);
            } else {
              images = [response.data.images];
            }
          }
        } catch (e) {
          console.error('解析图片数据失败:', e);
          images = [response.data.images];
        }
      }

      // 处理日期
      const date = response.data.date || 
                  (response.data.created_at ? response.data.created_at.split('T')[0] : null) || 
                  new Date().toISOString().split('T')[0];

      const diary = {
        ...response.data,
        images,
        date
      };

      this.setData({
        diary,
        loading: false
      });
    } catch (error) {
      console.error('Error loading diary:', error);
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none',
        duration: 2000
      });
      this.setData({ loading: false });
      setTimeout(() => {
        wx.navigateBack();
      }, 3000);
    }
  },

  previewImage(e) {
    const current = e.currentTarget.dataset.src;
    wx.previewImage({
      current,
      urls: this.data.diary.images
    });
  }
}); 